package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
@RequestMapping("/order/")
public class OrderController {

    @Reference(timeout = 7000)
    private OrderService orderService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("submit")
    public Result submit(@RequestBody Map<String, Object> map) {
        String code = null;
        try {
            String key = ValidateCodeController.REGISTERED_KEY + map.get("telephone");
            code = redisTemplate.opsForValue().get(key).toString();
            String telephone = map.get("telephone").toString();


            if (telephone != null && code != null && map.get("validateCode").equals(code)) {
                redisTemplate.delete(key);
                Result result = orderService.order(map);
                if (result.isFlag()) {
                    String p = JSON.parse("{'number':'" + telephone + "','orderDate':'" + map.get("orderDate") + "'}").toString();
                    SMSUtils.sendSms(SMSUtils.ORDER_SUCCESS, telephone, p);
                }
                return result;

            } else {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, code==null?"请发送验证码":"预约失败");
        }
    }

    @RequestMapping("findById")
    public Result findById(Integer id) {
        try {
            return orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
